package com.kedacom.freedomLabel.viewmodel.report;


import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.OnLifecycleEvent;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.kedacom.freedomLabel.AppExecutors;
import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.base.BaseViewModel;
import com.kedacom.freedomLabel.model.bean.Business;
import com.kedacom.freedomLabel.model.bean.BusinessCount;
import com.kedacom.freedomLabel.model.bean.BusinessGroup;
import com.kedacom.freedomLabel.model.bean.Category;
import com.kedacom.freedomLabel.model.bean.ReportGroupItem;
import com.kedacom.freedomLabel.model.bean.ReportSumItem;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.freedomLabel.model.db.DataCallback;
import com.kedacom.freedomLabel.model.db.DataLoader;
import com.kedacom.freedomLabel.model.db.dao.CategoryDao;
import com.kedacom.lego.message.LegoMessageManager;
import com.seray.scaleviewlib.utils.CacheDiskUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;


public class ReportSummaryViewModel extends BaseViewModel {

    /**
     * fragment的预览类型
     * 0 日报表
     * 1 月报表
     * 2 产品报表
     * 3 操作员报表
     */
    public MutableLiveData<Integer> reportType = new MutableLiveData<>();
    public Date currentDate = new Date(); // 当前日期
    // 产品报表时间条件
    public MutableLiveData<Date> startDate = new MutableLiveData<>(); // 开始时间
    public MutableLiveData<Date> endDate = new MutableLiveData<>(); // 结束时间
    // 日月报表时间条件
    public MutableLiveData<Date> currentDisplayDate = new MutableLiveData<>(); // 时间

    // 总览
    public MutableLiveData<BusinessCount> businessCount = new MutableLiveData<>();

    // 聚合
    public MutableLiveData<List<BusinessGroup>> businessGroup = new MutableLiveData<>();

    public String productId = ""; // 默认查询所有的
    public String cardNumber = ""; // 默认查询所有的

    // 所有的商品列表
    public MutableLiveData<List<Business>> allProduct = new MutableLiveData<>();

    // 所有的操作员
    public MutableLiveData<List<Business>> allOperator = new MutableLiveData<>();

    // 明细
    public MutableLiveData<List<Business>> businessList = new MutableLiveData<>();

    // 查询时间
    public long startTime = 0L;
    public long endTime = 0L;

    public void getSummary() {
        updateQueryTime();
        AppExecutors.getInstance().queryIO()
                .submit(() -> {
                    try {
                        BusinessCount count = AppDatabase.getInstance().businessDao()
                                .getBusinessCount(startTime, endTime);
                        businessCount.postValue(count);
                    } catch (Exception e) {
                        e.printStackTrace();
                        showToast(e.getMessage(), TOAST_ERROR);
                    }
                });
    }

    public void getSummaryGroup() {
        updateQueryTime();
        AppExecutors.getInstance().queryIO()
                .submit(() -> {
                    try {
                        if(reportType.getValue()==2){
                            if (TextUtils.isEmpty(productId)) {
                                businessGroup.postValue(AppDatabase.getInstance().businessDao()
                                        .getBusinessGroup(startTime, endTime));
                            } else {
                                businessGroup.postValue(AppDatabase.getInstance().businessDao()
                                        .getBusinessGroup(productId, startTime, endTime));
                            }
                        }else {
                            if (TextUtils.isEmpty(cardNumber)) {
                                businessGroup.postValue(AppDatabase.getInstance().businessDao()
                                        .getBusinessGroupWithOperator(startTime, endTime));
                            } else {
                                businessGroup.postValue(AppDatabase.getInstance().businessDao()
                                        .getBusinessGroupWithOperator(cardNumber, startTime, endTime));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        showToast(e.getMessage(), TOAST_ERROR);
                    }
                });
    }

    // 获取所有的产品种类 用来选择商品用
    public void getProductCategories() {
        AppExecutors.getInstance().queryIO()
                .submit(() -> {
                    try {
                        List<Business> products = AppDatabase.getInstance().businessDao()
                                .getBusinessCategories();
                        allProduct.postValue(products);
                    } catch (Exception e) {
                        e.printStackTrace();
                        showToast(e.getMessage(), TOAST_ERROR);
                    }
                });
    }

    // 获取所有的操作员 用来选择操作员
    public void getAllOperator() {
        AppExecutors.getInstance().queryIO()
                .submit(() -> {
                    try {
                        allOperator.postValue(AppDatabase.getInstance().businessDao().getBusinessOperators());
                    } catch (Exception e) {
                        e.printStackTrace();
                        showToast(e.getMessage(), TOAST_ERROR);
                    }
                });
    }


    // 更新开始和结束时间
    public void updateQueryTime() {
        if (reportType.getValue() == null)
            return;

        if (reportType.getValue() == 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDisplayDate.getValue());

            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            startTime = calendar.getTimeInMillis();

            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            endTime = calendar.getTimeInMillis();
        } else if (reportType.getValue() == 1) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDisplayDate.getValue());

            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            startTime = calendar.getTimeInMillis();

            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            endTime = calendar.getTimeInMillis();
        } else if (reportType.getValue() == 2 || reportType.getValue() == 3) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate.getValue());

            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            startTime = calendar.getTimeInMillis();

            calendar.setTime(endDate.getValue());
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            endTime = calendar.getTimeInMillis();
        }
    }

    // 按开始和结束时间 产品类型查询

    //按种类 日期 查询详情


    public MutableLiveData<String> mUpper = new MutableLiveData<>();
    public MutableLiveData<String> mLow = new MutableLiveData<>();
    public MutableLiveData<List<ReportSumItem>> mSummaryData = new MutableLiveData<>();
    public MutableLiveData<List<ReportGroupItem>> mReportGroupItem = new MutableLiveData<>();
    public MutableLiveData<String[]> mColumnNamesLiveData = new MutableLiveData<>();
    public MutableLiveData<Category> mCategory = new MutableLiveData<>();


    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void prepareUpperAndLow() {
        String usageCategory = CacheDiskUtils.getInstance(Options.LOCAL_USAGE_CATEGORY_FILE_NAME)
                .getString(Category.class.getSimpleName());
        if (usageCategory == null || usageCategory.isEmpty()) {
            LegoMessageManager.getInstance().sendEmptyMessage(Options.MSG_REPORT_NO_CATEGORY);
        } else {
            CategoryDao dao = AppDatabase.getInstance().categoryDao();
            DataLoader.get(dao, usageCategory, new DataCallback<List<Category>>() {
                @Override
                public void success(@Nullable List<Category> data) {
                    if (data != null && !data.isEmpty()) {
                        mCategory.setValue(data.get(0));
//                        mUpper.setValue(mCategory.getValue().upper);
//                        mLow.setValue(mCategory.getValue().low);
                        String[] columnNames = mCategory.getValue().columnNames;
                        mColumnNamesLiveData.setValue(columnNames);
                    } else {
                        LegoMessageManager.getInstance().sendEmptyMessage(Options.MSG_REPORT_NO_CATEGORY);
                    }
                }

                @Override
                public void error(@Nullable String errorMessage) {
                    LegoMessageManager.getInstance().sendEmptyMessage(Options.MSG_REPORT_NO_CATEGORY);
                }
            });
        }
    }
}
